/*
 * Copyright 2009 Yannick Stucki (yannickstucki.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.yannickstucki.android.musicqueue.old;

import com.yannickstucki.android.musicqueue.util.Logger;

import android.media.MediaPlayer;

/**
 * A thread that updates the progress bar periodically.
 * 
 *ake progress bar changeable by track ball.
 * 
 * @author Yannick Stucki (yannickstucki@gmail.com)
 * 
 */
public class ProgressUpdater extends Thread {

  /**
   * The interval in milliseconds when the progress bar gets updated.
   */
  private static final int UPDATE_INTERVAL = 200;

  /**
   * A flag used to stop the thread.
   */
  private volatile boolean stop = false;

  /**
   * Requests that this thread should stop.
   */
  public synchronized void requestStop() {
    stop = true;
  }

  /**
   * Checks whether this thread should stop.
   */
  private synchronized boolean stopRequested() {
    return stop;
  }

  /**
   * A reference to the UI class is needed to update the progress bar.
   */
  private MusicQueue mq;

  /**
   * Shouldn't be needed. See todo below.
   */
  private MediaPlayer mediaPlayer;

  /**
   * The constructor sets necessary references.
   */
  public ProgressUpdater(MusicQueue mq, MediaPlayer mediaPlayer) {
    this.mq = mq;
    this.mediaPlayer = mediaPlayer;
  }

  @Override
  public void run() {
    while (true) {
      if (stopRequested()) {
        return;
      }
      if (mq != null && mq.playerUiPortrait != null
          && !mq.playerUiPortrait.seeking) {
        //those 2 conditions were satisfied before launching this
        // thread then the if could go away.
        mq.playerUiPortrait.seekBar.setProgress(mediaPlayer
            .getCurrentPosition());
      }
      try {
        Thread.sleep(UPDATE_INTERVAL);
      } catch (InterruptedException e) {
        Logger.out(e);
      }
    }
  }
}
